<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :md="5" :sm="12" v-if="isSuperAdmin">
            <a-form-item label="租户名称">
              <a-input v-model="queryParam.tenantName" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="5">
            <a-form-item label="用户名">
              <a-input v-model="queryParam.userName" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="12">
            <a-form-item label="状态">
              <a-select v-model="queryParam.status" placeholder="请选择" default-value="">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="true">启用</a-select-option>
                <a-select-option value="false">锁定</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="12">
            <a-form-item label="部门">
              <a-input v-model="queryParam.deptName" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="3" :sm="12">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'left', overflow: 'hidden' } || {} ">
              <a-tooltip placement="topLeft" title="查询" arrow-point-at-center>
                <a-button shape="circle" @click="$refs.table.refresh(true)" icon="search"/>
              </a-tooltip>
              <a-tooltip placement="topLeft" title="重置" arrow-point-at-center>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}" icon="sync"/>
              </a-tooltip>
              <!--<a @click="toggleAdvanced" style="margin-left: 8px">-->
              <!--{{ advanced ? '收起' : '展开' }}-->
              <!--<a-icon :type="advanced ? 'up' : 'down'"/>-->
              <!--</a>-->
            </span>
          </a-col>
          <!--<a-col :md="!advanced && 8 || 24" :sm="24">-->
          <!--<span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">-->
          <!--<a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>-->
          <!--<a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>-->
          <!--<a @click="toggleAdvanced" style="margin-left: 8px">-->
          <!--{{ advanced ? '收起' : '展开' }}-->
          <!--<a-icon :type="advanced ? 'up' : 'down'"/>-->
          <!--</a>-->
          <!--</span>-->
          <!--</a-col>-->
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button v-show="addEnable" type="primary" shape="round" icon="plus-circle" @click="$refs.modal.add()">添加</a-button>
      <a-button v-show="delEnable && selectedRowKeys.length > 0" shape="round" type="danger" icon="delete" @click="onClick(selectedRowKeys)">删除</a-button>
      <a-button v-show="exportEnable" type="primary" shape="round" icon="export" @click="$refs.user_export.export(queryParam)">导出</a-button>
    </div>
    <s-table
      ref="table"
      row-key="id"
      :columns="columns"
      :data="loadData"
      showPagination="auto"
      :rowSelection="delEnable ? {selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: getCheckboxProps} : null"
      :showTotal="showTotal"
      :scroll="{ x: 1000 }">
      <span slot="customTenantTitle"><a-icon type="home" theme="twoTone"/>  租户</span>
      <span slot="customDeptTitle"><a-icon type="apartment" :style="{ fontSize: '16px', color: '#4F99FF' }"/>  部门</span>
      <span slot="customLoginNameTitle"><a-icon type="smile" :style="{ fontSize: '16px', color: '#4F99FF' }"/>  登录名</span>
      <span slot="customUserNameTitle"><a-icon type="user" :style="{ fontSize: '16px', color: '#4F99FF' }"/>  用户名</span>
      <span slot="customRoleTitle"><a-icon type="team" :style="{ fontSize: '16px', color: '#4F99FF' }"/>  角色</span>
      <span slot="customStatusTitle"><a-icon type="lock" theme="twoTone"/>  状态</span>
      <span slot="customSexTitle"><a-icon type="man" :style="{ fontSize: '16px', color: '#4F99FF' }"/>|<a-icon type="woman" :style="{ fontSize: '16px', color: '#eb2f96' }"/>性别</span>
      <span slot="customPhoneTitle"><a-icon type="mobile" theme="twoTone"/>  手机号</span>
      <span slot="customActionTitle"><a-icon type="form" :style="{ fontSize: '16px', color: '#4F99FF' }"/>  操作</span>
      <span slot="customCreateTimeTitle"><a-icon type="clock-circle" theme="twoTone"/>  创建时间</span>
      <span slot="customLoginTimeTitle"><a-icon type="clock-circle" theme="twoTone"/>  最后登录时间</span>
      <span slot="sysRoles" slot-scope="sysRoles">
        <a-tag
          v-for="role in sysRoles"
          :key="role.roleName"
          :color="role.roleName === 'loser' ? 'volcano' : role.length > 5 ? 'geekblue' : 'green'"
        >
          {{ role.roleName.toUpperCase() }}
        </a-tag>
      </span>
      <span slot="sex" slot-scope="sex">
        <a-tag
          :key="sex"
          :color="sex === '0' ? 'blue' : '#eb2f96'"
        >
          {{ sex === '0'? '男': sex === '1' ? '女' : '未知' }}
        </a-tag>
      </span>
      <span slot="status" slot-scope="text, record">
        <a-switch :disabled="record.id === '1' || !editEnable" :checked="text" @change="changeStatus(record,!text)">
          <a-icon slot="checkedChildren" type="unlock" />
          <a-icon slot="unCheckedChildren" type="lock" />
        </a-switch>
      </span>

      <span slot="action" slot-scope="text, record">
        <template>
          <a-dropdown>
            <a-menu slot="overlay" v-if="editEnable || delEnable || resetPasswordEnable">
              <a-menu-item v-show="editEnable"><a @click="handleEdit(record)"><a-icon type="edit" theme="filled"/> 编辑</a></a-menu-item>
              <a-menu-item v-show="delEnable"><a @click="onClick([record.id])"><a-icon type="delete" theme="filled"/> 删除</a></a-menu-item>
              <a-menu-item v-show="resetPasswordEnable"><a @click="resetPassWord(record)"><a-icon type="unlock" theme="filled"/> 重置密码</a></a-menu-item>
            </a-menu>
            <a> <a-button type="dashed" icon="bars"/></a>
          </a-dropdown>
        </template>
      </span>
    </s-table>
    <user-modal ref="modal" @ok="handleOk"/>
    <user-reset-pwd-modal ref="pwdmodal"/>
    <user-export-modal ref="user_export"/>
  </a-card>
</template>
<script>
  import { getUserList, changeStatus, delUser } from '@/api/system'
  import { STable } from '@/components'
  import { checkPermission, checkUserSuperAdmin } from '@/utils/permissions'
  import { filterColumns } from '@/utils/util'
  // import notification from 'ant-design-vue/es/notification'
  import UserResetPwdModal from '../modules/UserResetPwdModal'
  import UserModal from '../modules/UserModal'
  import message from 'ant-design-vue/es/message'
  import UserExportModal from '../modules/UserExportModal'
  const statusMap = {
    true: {
      status: 'success',
      text: '正常'
    },
    false: {
      status: 'processing',
      text: '禁用'
    }
  }
  const columns = [
    { dataIndex: 'tenantName', width: 150, align: 'left', ellipsis: true, slots: { title: 'customTenantTitle' } },
    { dataIndex: 'deptName', width: 150, align: 'left', ellipsis: true, slots: { title: 'customDeptTitle' } },
    { width: 150, dataIndex: 'loginName', align: 'center', sorter: true, slots: { title: 'customLoginNameTitle' } },
    { width: 150, dataIndex: 'userName', key: 'userName', align: 'center', sorter: (a, b) => a.age - b.age, slots: { title: 'customUserNameTitle' } },
    {
      width: 150,
      key: 'sysRoles',
      dataIndex: 'sysRoles',
      align: 'center',
      scopedSlots: { customRender: 'sysRoles' },
      slots: { title: 'customRoleTitle' }
    },
    { dataIndex: 'status', width: 150, align: 'center', scopedSlots: { customRender: 'status' }, slots: { title: 'customStatusTitle' } },
    { dataIndex: 'sex',
      key: 'sex',
      width: 150,
      align: 'center',
      sorter: (a, b) => a.address - b.address,
      scopedSlots: { customRender: 'sex' },
      slots: { title: 'customSexTitle' }
      },
    { dataIndex: 'phone', key: 'phone', width: 150, align: 'center', slots: { title: 'customPhoneTitle' } },
    { dataIndex: 'loginDate', width: 150, align: 'center', slots: { title: 'customLoginTimeTitle' } },
    { dataIndex: 'createTime', width: 150, align: 'center', slots: { title: 'customCreateTimeTitle' } },
    {
      key: 'operation',
      fixed: 'right',
      align: 'center',
      width: 100,
      scopedSlots: { customRender: 'action' },
      slots: { title: 'customActionTitle' }
    }
  ]

  export default {
    components: {
      UserExportModal,
      getUserList,
      STable,
      UserResetPwdModal,
      UserModal
    },
    data () {
      return {
        data: [],
        columns,
        currentStep: 1,
        // 查询参数
        queryParam: {},
        // 高级搜索 展开/关闭
        advanced: false,
        editEnable: checkPermission('system:user:edit'),
        delEnable: checkPermission('system:user:remove'),
        resetPasswordEnable: checkPermission('system:user:resetPassword'),
        addEnable: checkPermission('system:user:add'),
        exportEnable: checkPermission('system:user:export'),
        showTotal: true,
        selectedRowKeys: [],
        selectedRows: [],
        isSuperAdmin: false,
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          const requestParameters = Object.assign({}, parameter, this.queryParam)
          return getUserList(requestParameters)
            .then(res => {
              this.$set(this, 'selectedRowKeys', [])
              return res.data
            }).catch(res => {
              message.error(((res.response || {}).data || {}).message || res.message)
            })
        }
      }
    },
    created () {
      this.isSuperAdmin = checkUserSuperAdmin()
      if (!this.isSuperAdmin) {
        const arr = new Array('tenantName')
        this.columns = filterColumns(columns, arr)
      }
    },
    filters: {
      statusFilter (type) {
        return statusMap[type].text
      },
      statusTypeFilter (type) {
        return statusMap[type].status
      }
    },
    methods: {
      getCheckboxProps: record => ({
        props: {
          disabled: record.id === '1'
        }
      }),
      onSelectChange (selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      handleEdit (record) {
        this.$refs.modal.edit(record)
      },
      resetPassWord (record) {
        this.$refs.pwdmodal.edit(record)
      },
      async changeStatus (record, checked) {
        await changeStatus({ id: record.id, status: checked }).then(res => {
          this.$refs.table.refresh()
          if (checked) {
            message.success('解锁成功')
          } else {
            message.success('锁定成功')
          }
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      // onChange,
      onClick (ids) {
        const self = this
        this.$confirm({
          title: '你确定删除该用户吗?',
          content: h => <div style="color:red;">用户删除将永久不能恢复</div>,
          onOk () {
            delUser(ids).then(res => {
              self.$refs.table.refresh()
              message.success('删除用户成功')
              self.selectedRowKeys = []
            }).catch(res => {
              message.error(((res.response || {}).data || {}).message || res.message)
            })
          },
          onCancel () {
            self.selectedRowKeys = []
          }
        })
      },
      exportUser () {

      }
    }
  }
</script>

<style lang="less" scoped>
/deep/ .ant-table-tbody > tr > td {
  padding: 10px;
}
</style>
